package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;


    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //校验参数
        Integer size = dto.getSize();
        if (size==null||size<=0){
            size=10;
        }
        dto.setSize(size);
        //频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间
        if (dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : articleList) {
            //获取文章封面字段
            String images = apArticle.getImages();
            if (StringUtils.isNotBlank(images)) {
                //将封面以逗号切割
               images=Arrays.stream(images.split(","))
                       //加上前缀
                       .map(url->webSite+url)
                       .collect(Collectors.joining(","));
               apArticle.setImages(images);
            }

            //拼接静态页面的访问前缀路径
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        return ResponseResult.okResult(articleList);
    }

    /**
     * wmNews  查询
     * ap_article   ap_article_confg   ap_article_content  保存3表数据
     * wmNews  修改  9  article_id
     * @param newsId 文章id
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    public void publishArticle(Integer newsId) {
        //查询并校验自媒体文章
        WmNews wmNews = getWmNewsById(newsId);

        //TODO 封装ApArtcle
        ApArticle apArticle = parseApArticle(wmNews);

        //保存或修改文章
        saveOrUpdateApArticle(apArticle);

        //保存关联配置 和 文章内容
        saveConfigAndContent(apArticle,wmNews);

        //TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);

        //更新WmNews状态
        updateWmNews(wmNews,apArticle);


        //TODO 通知es索引库添加文章索引

    }

    /**
     * 更新WmNews状态
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(WmNews wmNews, ApArticle apArticle) {
        //更新文章状态为9
        wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
        //关联文章id
        wmNews.setArticleId(apArticle.getId());

        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程修改自媒体文章状态失败");
        }
    }

    /**
     * 保存关联配置 和 文章内容
     * @param apArticle
     * @param wmNews
     */
    private void saveConfigAndContent(ApArticle apArticle, WmNews wmNews) {
        //保存配置
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);// 是否允许评论
        apArticleConfig.setIsForward(true);//// 是否允许 转发
        apArticleConfig.setIsDown(false);// 是否下架
        apArticleConfig.setIsDelete(false);// 是否删除
        apArticleConfigService.save(apArticleConfig);

        //保存内容
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentService.save(apArticleContent);
    }

    /**
     * 保存或修改文章
     * @param apArticle
     */
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        //修改删除关联文章信息
        if (apArticle.getId()==null){
            //直接保存文章
            apArticle.setViews(0);
            apArticle.setLikes(0);
            apArticle.setComment(0);
            apArticle.setCollection(0);
            save(apArticle);
        }else {
            // 删除关联的 文章配置信息  和  文章详情信息
            apArticleConfigService.remove(Wrappers.<ApArticleConfig>lambdaQuery()
                                                    .eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentService.remove(Wrappers.<ApArticleContent>lambdaQuery()
                                                    .eq(ApArticleContent::getArticleId,apArticle.getId()));
            updateById(apArticle);
        }
    }

    /**
     * 封装ApArtcle
     * @param wmNews
     * @return
     */
    private ApArticle parseApArticle(WmNews wmNews) {
        //news转artcle
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        //设置特殊字段
        apArticle.setId(wmNews.getArticleId());
        apArticle.setLayout(wmNews.getType());
        apArticle.setFlag((byte) 0);
        //设置频道
        ResponseResult<AdChannel> channel = adminFeign.findOne(wmNews.getChannelId());
        if (!channel.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询频道信息失败");
        }
        AdChannel adChannel = channel.getData();
        apArticle.setChannelName(adChannel.getName());
        //设置作者
        ApAuthor author = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());
        return apArticle;
    }

    /**
     * 查询并校验自媒体文章
     * @param newsId
     * @return
     */
    private WmNews getWmNewsById(Integer newsId) {
        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsById.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id: {}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"文章发布失败 远程调用自媒体文章接口失败");
        }
        WmNews wmNews = wmNewsById.getData();
        if (wmNews==null){
            log.error("文章发布失败 未获取到自媒体文章信息  文章id: {}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章发布失败 未获取到自媒体文章信息");
        }
        //  检查文章状态是否已通过
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(wmNews.getStatus())
                && !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(wmNews.getStatus())) {
            log.error("文章发布失败 文章状态不为 4 或 8， 不予发布 , 文章id : {}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章状态不为 4 或 8， 不予发布");
        }
        return wmNews;
    }
}